package com.seqb.server.controller;

import com.seqb.common.ResultVo;
import com.seqb.common.controller.BaseController;
import com.seqb.server.service.PublicService;
import com.seqb.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/public")
public class PublicController extends BaseController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PublicService publicService;


    @ResponseBody
    @RequestMapping("/verify/captcha")
    public Map<String, Object> verify(String jym, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String requestUrl = "http://query.ruankao.org.cn//score/VerifyCaptcha";
            HttpHeaders headers = new HttpHeaders();
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("captcha", jym);
            List<String> cookieList = new ArrayList<>();
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
            }
            headers.put("Cookie", cookieList);
            result = restTemplate.postForObject(requestUrl, new HttpEntity(map, headers), Map.class);
        } catch (Exception e) {
            result.put("flag", 0);
            result.put("msg", "接口调用失败");
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/score/search")
    public Map<String, Object> search(String stage, String xm, String zjhm, String jym, String select_type, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String requestUrl = "http://query.ruankao.org.cn//score/result";
            HttpHeaders headers = new HttpHeaders();
            List<String> cookieList = new ArrayList<>();
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
            }
            headers.put("Cookie", cookieList);
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("stage", stage);
            map.add("xm", xm);
            map.add("zjhm", zjhm);
            map.add("jym", jym);
            map.add("select_type", select_type);
            result = restTemplate.postForObject(requestUrl, new HttpEntity(map, headers), Map.class);
        } catch (Exception e) {
            result.put("flag", 0);
            result.put("msg", "接口调用失败");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 生成验证码
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletResponse response) {
        try {
            //发起请求图片验证码
            String requestUrl = "http://query.ruankao.org.cn//score/captcha";
            ResponseEntity<Resource> responseEntity = restTemplate.getForEntity(requestUrl, Resource.class);

            //将cookie写入浏览器
            List<String> cookies = responseEntity.getHeaders().get("Set-Cookie");
            for (String cookieStr : cookies) {
                String[] cookieArr = cookieStr.split(";");
                String cookieItem = cookieArr[0];
                Cookie cookie = new Cookie(cookieItem.split("=")[0], cookieItem.split("=")[1]);
                cookie.setPath("/");
                try {
                    URLEncoder.encode(cookieItem.split("=")[1], "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.addCookie(cookie);
            }

            //输出图片验证码
            InputStream inStream = responseEntity.getBody().getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] data = outStream.toByteArray();
            inStream.read(data);
            inStream.close();
            response.setContentType("image/jpg");
            OutputStream os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取科目类别
     */
    @ResponseBody
    @RequestMapping("/subject/type")
    public ResultVo subjectType(@RequestParam Map<String, Object> params) {
        return publicService.getSubjectType(params);
    }

    /**
     * 获取科目
     */
    @ResponseBody
    @RequestMapping("/subject")
    public ResultVo subject(@RequestParam Map<String, Object> params) {
        return publicService.getSubject(params);
    }

    /**
     * 获取科目试卷
     */
    @ResponseBody
    @RequestMapping("/subject/paper")
    public ResultVo subjectPaper(@RequestParam Map<String, Object> params) {
        return publicService.getSubjectPaper(params);
    }

    /**
     * 获取试卷
     */
    @ResponseBody
    @RequestMapping("/paper")
    public ResultVo paper(@RequestParam Map<String, Object> params) {
        return publicService.getPaper(params);
    }

    /**
     * 获取试卷的题目
     */
    @ResponseBody
    @RequestMapping("/paper/question")
    public PageUtils paperQuestion(@RequestParam Map<String, Object> params) {
        return publicService.getPaperQuestion(params);
    }

    /**
     * 获取报考指南列表
     */
    @ResponseBody
    @RequestMapping("/guide")
    public PageUtils getGuide(@RequestParam Map<String, Object> params) {
        return publicService.getGuide(params);
    }

    /**
     * 获取报考指南详细
     */
    @ResponseBody
    @RequestMapping("/getGuideDO")
    public ResultVo getGuideDO(@RequestParam Map<String, Object> params) {
        return publicService.getGuideDO(params);
    }
}
